<?php

chdir(dirname(__FILE__)."/../..");
$path = getcwd();
chdir("../");
$path3 = getcwd();
chdir(dirname(__FILE__));
#debug($path3 , $path2);
include_once $path3."/lib/core.class.php";

class OrdersList extends IPlugin 
{
    var $color;
    
    function OrdersList($parent = null)
    {
        IPlugin::IPlugin($parent);
        $this->tplfolder = dirname(__FILE__)."/tpl";
        $this->color = "blue";
    }
    
    function getPluginTag() { return "orderslist"; }
    function getPluginName() { return "Orders List Plugin"; }
    function getPluginVersion() { return "1.0.0"; }
    
    function getProperty($p = null)
    {
        if(null == $p)
        {
            return array("MenuTitle", "MenuBlockTitle");
        }
        $result = "";
        switch ($p)
        {
            case "MenuBlockTitle": { return "Online Shop"; } break;
            case "MenuTitle" : { return "Orders"; } break;
        };
        return $result;
    }
    
    // ----------------------------------------------------------------------------------
    // --- [ Handling all actions ] -----------------------------------------------------
    // ----------------------------------------------------------------------------------

    function doAction($params)
    {
        if(null != ($result = IPlugin::doAction($params)))
        {
            return $result;
        }

               if ( "doDelete" == $_GET['action'])
        {
            $uid = $_GET['id'];
            if(empty($uid) || $uid<0 || !is_numeric($uid) )
            {
                header("location: ./?".$this->getURL());
                exit();
            }
            $core = getCoreInstance();
            $db = $core->getProperty("db");
            
            $sql = "delete from orders where id=".str2db($uid)."";
            $db->Exec($sql);
            $sql = "delete from purchaseitems where order_id=".str2db($uid)."";
            $db->Exec($sql);

            $sql = "delete from clients_orders where order_id=".str2db($uid)."";
            $db->Exec($sql);
        

                header("location: ./?".$this->getURL());
                exit();

        }



        switch ($_POST["event"]) {
            case "Submit_Order": {
                global $_P;
            $core = &getCoreInstance();
            $db = &$core->getProperty("db");
            $Sel_Status=$_P["Sel_Status"];
            $tn = $_P['order_tn'];
            $id=$_P["id"];
            $provider = $_P['provider'];
            $db->Exec("update orders set status='$Sel_Status',order_tn='$tn',provider='$provider' where id=$id");
            $message_status=array(
                                    1 => "Your order put in our database",
                                    2 => "Your order is in progress",
                                    3 => "Your order is succsesfull complete",
                                 );
            $id=$_P["id"];
            $id_status=$db->getone("select status from orders where id=$id");

                       
            if ($_P["Check_Email"]) 
            {
                $msg = "
                <html>
                <body>
                    <b>Your order tracking number is : {$tn} <br />
                    <b>Postage service via : {$provider} <br />
                    <b>Text of message:</b>   <br />
                    $message_status[$id_status] <br /> <br />
               
                <body>
                </html>";
                $mail = $core->getSnippet("email");
                //$render = &$core->framework->smarty;
                $m_from=$db->getone("select s_value from settings where `s_key`='mail'");
                $m_to=$db->getone("select address1 from orders where id=$id");
                
                $params = array(
                    "to" => $m_to,
                    "from" => $m_from,
                    "body" => $msg,
                    "subject" => "Order status",
                    "html" => "1",  // 1/0                              
                                );
                                
                    $mm=$mail->doAction($params);                               
            }

            

            } break;
          
            default:
            break;
        }
        
        
        
        
    }


    // ----------------------------------------------------------------------------------
    // --- [ Render pages ] -------------------------------------------------------------
    // ----------------------------------------------------------------------------------

    function Render($params)
    {
        global $_G;
        if(null != ($result = IPlugin::Render($params)))
        {
            return $result;
        }
        
        $core = &getCoreInstance();
        $db = $core->getProperty("db");
        $framework = $core->getProperty("framework");
        $render = $framework->smarty;
        $render->assign("baseurl", "?".$this->getURL()."&page=".$_G["page"]);

        $page = "";

        switch ($_G["page"]) {
            case "view":
                $page = $this->getOrderView($core, $render, $db);
                break;
            case "print":
                $page = $this->getOrderView($core, $render, $db);
                break;
            case "printlabel":
                $page = $this->getPrintLabelView($core, $render, $db);
                break;
            default:
                $page = $this->renderOrdersList($render);
                break;
        }

        return $render->fetch("file:".$this->tplfolder."/".$page);
    }
    
    // ----------------------------------------------------------------------------------
    // --- [ Render Order View Page ] ---------------------------------------------------
    // ----------------------------------------------------------------------------------

    function checkImage($file, $folder, &$core, $default="")
    {
        if(file_exists($core->config["file_root"].$folder.$file))
        {
            return $folder.$file;
        }
        return $folder.$default;
    }

    function getOrderView(&$core, &$render, &$db)
    {
        $render->assign("bar_txt", trim($core->config['system']['barcode_txt']));
        $z = $db->getAll("select * from orders where id={$_GET[id]}");
        $p = $db->getAll("select * from purchaseitems where order_id={$_GET[id]}");
        if(!count($z))
        {
            header("location: ./path=orderslist");
            exit();
        }
        $z = $z[0];
        
        $price = 0;
        foreach($p as $k => $w)
        {
            $value_warranty = $db->getOne("select warrantytype_price from products_warranty_types where warrantytype_id = {$p[$k][warranty]}");
            $p[$k]['warranty_num'] = @number_format($value_warranty * $p[$k]["qty"], 2, '.', ',');
            $p[$k]["image"] = $this->checkImage($p[$k]["image"], "/inventory/", $core, "noimage_small.jpg");
            $price += $p[$k]["qty"]*$p[$k]["price"] + $p[$k]['warranty_num'];
            $p[$k]['price_prod'] = @number_format($p[$k]["price"], 2, '.', ',');
            $p[$k]['price_num_prod'] = @number_format($p[$k]["qty"] * $p[$k]["price"] + $value_warranty * $p[$k]["qty"], 2, '.', ',');
            $p[$k]['reason'] = db2str($p[$k]['reason']);
        }
        

        if ("" == $z['saddress1'] && "" == $z['saddress2'])
        {
            $z['sfname'] = $z['fname'];
            $z['slname'] = $z['lname'];
            $z['saddress1'] = $z['address1'];
            $z['saddress2'] = $z['address2'];
            $z['scity'] = $z['city'];
            $z['sstate'] = $z['state'];
            $z['szip'] = $z['zip'];
            $z['scountry'] = $z['country'];
        }

        
        $id=$_GET[id];
        $z['discount'] = @number_format($z['discount'],2,'.',',');
        $z['price'] = @number_format($z['price'],2,'.',',');
        $render->assign("id", $id);
        $z['ccnumber'] = getsafeccnumber($z['ccnumber']);
        $render->assign("order", $z);
        $render->assign("items", $p);
        $render->assign("price", @number_format($price, 2, '.', ','));
        $render->assign("form_url", "?".$this->getURL());


        $ship = $db->getrow("select * from shipment where shipment_id='".$z['shipment']."'");
        $ship['shipment_price'] = @number_format($ship['shipment_price'],2,'.',',');
        $render->assign("shipment", $ship );
    
        $result=$db->getall("select id, name from order_status");
        $render->assign("Status_List", $result );
    
        $postagevia=$db->getall("select title from postage_via");
        $render->assign("postage_list", $postagevia);
    
        $z_st=$z["status"];
        $render->assign("Current_Status", $z["status"]);


        
        if ($_GET['page'] == "print")
        {
            return "ordersdetailsprint.tpl.php";
        }
        elseif($_GET['page'] == "view")
        {
            return "ordersdetails.tpl.php";
        }
    }
    
    // ----------------------------------------------------------------------------------
    // --- [ Generate Customers List ] --------------------------------------------------
    // ----------------------------------------------------------------------------------
    
    function cb_rndOS($data)
    {
        $dt = array(
                array($data["id"], "align=\"center\""),
                array(date("m/d/Y H:i", strtotime($data["pubdate"])), "align=\"center\""),
                array($data["fname"]." ".$data["lname"], ""),
                array("\$" . @number_format($data["price"], 2, '.', ','), "align=center"),
                array($data["status_name"], "align=center"),
                array(("ord" == $data["type_order"] ? "Order" : "Return"), "align=center"),
                array("<a href=\"?".$this->getURL()."&page=view&id={$data[id]}\">view</a>"
                    ."&nbsp;&nbsp;"
                    ."<a href=\"?".$this->getURL()."&action=doDelete&id={$data[id]}\">delete</a>", "align=\"center\""),
                );
        return $dt;
    }

    function renderOrdersList(&$render)
    {
        $core = &getCoreInstance();
        $db = $core->getProperty("db");
        
        $pg = &$core->getSnippet("paginator");
        $params = array(
                    "cb_class" => &$this,
                    "cb_func" => cb_rndOS,
                    "urlbase" => $this->getURL(),
                    "caption" => "Clients Orders list",
                    "emptymsg" => "No orders was placed",
                    "header" => array("ID", "Order Date", "Client", "Summary Price", "Order Status", "Order/ReturnOrder", "Actions"),
                    "items" => "",
                    "source" => "sql", // -- sql, array
                    "sql_items" => "select o.id, o.pubdate, o.fname, o.lname, o.price, os.name as status_name, o.type_order as type_order  from orders o, order_status os where o.status=os.id order by o.pubdate desc",
                    "sql_count" => "select count(*) from orders",
                    "ippg" => 10, // -- items per page
                    "nppv" => 5, // -- number pages per view
                    );
        $HTML = $pg->Render($params);
        $render->assign("orders", $HTML);
  
        return "orderslist.tpl.php";

    }
    
    function getPrintLabelView(&$core, &$render, &$db){
        $render->assign("bar_txt", trim($core->config['system']['barcode_txt']));
        $render->assign("logo_name", trim($core->config['system']['logo_name']));
        $render->assign("httproot", $core->config['system']['http_root']);


        $render->assign("line1", $core->config['barcode']['line1']);
        $render->assign("line2", $core->config['barcode']['line2']);
        $render->assign("line3", $core->config['barcode']['line3']);
        $render->assign("line4", $core->config['barcode']['line4']);
        $render->assign("line5", $core->config['barcode']['line5']);

        $render->assign("ocode", $_GET['id']);

        $z = arrayDb2str($db->getrow("select * from orders where id={$_GET[id]}"));
        if('' != $z['sfname'] and '' != $z['slname']){
        $z['fname'] = $z['sfname'];
        $z['lname'] = $z['slname'];
        }
        if('' != $z['saddress1'] and '' != $z['saddress2']){
        $z['adress1'] = $z['saddress1'];
        $z['adress2'] = $z['saddress2'];
        }
    
        if('' != $z['scity']){
        $z['city']    = $z['scity'];
        }
    
        if('' != $z['sstate']){
        $z['state']    = $z['sstate'];
        }
    
        if('' != $z['szip']){
        $z['zip']    = $z['szip'];
        }
    
        if('' != $z['shipping_ups_service']){
        $sh = $z['shipping_ups_service'];
        }
        else{
        $sh = $z['provider'];
        }
    
        $tn = $z['order_tn'];
        
            $render->assign("track_number", $tn);
            $render->assign("postal", $sh);
    
            $render->assign("order", $z);
        return "_printLabel.tpl.php";
    }
      

};


?>